package cn.pacom.admin.core.tools.web;

/**
 * @author zhanghl
 * @Date 2020/7/27 15:42
 */

import java.io.IOException;

import javax.annotation.PostConstruct;

import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.thingsboard.rest.client.RestClient;
import org.thingsboard.server.common.data.page.PageData;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.ISysRoleService;

import cn.pacom.admin.core.tools.config.ThingsboardRestConfig;
import cn.pacom.iot.tools.model.bean.R;
import cn.pacom.iot.tools.model.request.PacomDeviceBindReq;
import cn.pacom.iot.tools.model.request.PacomDeviceListQueryReq;
import cn.pacom.iot.tools.model.vo.PacomDeviceListVo;

/**
 * 工具包 销售数据管理
 */
@RestController
@RequestMapping("/pacom/tools/saledevice")
public class SaleDeviceController extends BaseController {
  @Autowired
  private ISysRoleService roleService;

  @Autowired
  private RestClient restClient;

  @Autowired
  private ThingsboardRestConfig config;

  ObjectMapper objectMapper = new ObjectMapper();

  private String baseUri = "/api/pacomdevice";

  @PostConstruct
  public void init(){
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  }

  protected String getUri(String uri) {
    return config.getBaseUrl() + baseUri + uri;
  }

  @PreAuthorize("@ss.hasPermi('pacom:tools:saledevice:list')")
  @GetMapping("/list")
  public TableDataInfo list(PacomDeviceListQueryReq req) {
    req.setPage(req.getPage() - 1);
    String resultStr = this.restClient.getRestTemplate()
                                      .postForObject(getUri("/getDevices"), req, String.class);

    //    R<PageData<PacomDeviceListVo>> result =
    //      JSON.parseObject(resultStr, new TypeReference<R<PageData<PacomDeviceListVo>>>() {
    //      });

    R<PageData<PacomDeviceListVo>> result = null;
    TableDataInfo rspData = new TableDataInfo();
    try {
      logger.debug("response:{}",resultStr);
      result = objectMapper.readValue(resultStr, new TypeReference<R<PageData<PacomDeviceListVo>>>() {
      });

      rspData.setCode(HttpStatus.SUCCESS);
      rspData.setMsg("查询成功");
      rspData.setRows(result.getData()
                            .getData());
      rspData.setTotal(result.getData()
                             .getTotalElements());

    } catch (IOException e) {
      e.printStackTrace();
    }

    return rspData;

  }

  /**
   * 销售设备数据管理
   */
  @PreAuthorize("@ss.hasPermi('pacom:tools:saledevice:add')")
  @Log(title = "销售设备数据管理", businessType = BusinessType.INSERT)
  @PostMapping
  public AjaxResult add(@Validated @RequestBody PacomDeviceListVo request) {
    String uri = getUri("/save");

    try {
      RestTemplate restTemplate = this.restClient.getRestTemplate();
      ResponseEntity<R> r = restTemplate.postForEntity(uri, request, R.class);

    } catch (HttpClientErrorException e) {
      return handlerError(e);
    }

    return toAjax(1);
  }

  private AjaxResult handlerError(HttpClientErrorException e) {
    String responseBodyAsString = e.getResponseBodyAsString();
    AjaxResult ajaxResult = toAjax(-1);
    String msg = JSONObject.parseObject(responseBodyAsString)
                           .getString("message");
    return AjaxResult.error(msg);
  }

  /**
   * 根据角色编号获取详细信息
   */
  @PreAuthorize("@ss.hasPermi('pacom:tools:saledevice:query')")
  @GetMapping(value = "/{id}")
  public AjaxResult getInfo(@PathVariable String id) {
    return AjaxResult.error("todo");
    //    return AjaxResult.success(roleService.selectRoleById(roleId));
  }


  /**
   * 修改保存角色
   */
  @PreAuthorize("@ss.hasPermi('pacom:tools:saledevice:edit')")
  @Log(title = "销售设备数据管理", businessType = BusinessType.UPDATE)
  @PutMapping
  public AjaxResult edit(@Validated @RequestBody PacomDeviceListVo request) {
    String uri = getUri("/save");

    try {
      R<String> r = this.restClient.getRestTemplate()
                                   .postForObject(uri, request, R.class);
    } catch (HttpClientErrorException e) {
      return handlerError(e);
    }

    return toAjax(1);
  }

  /**
   * 解绑
   */
  @PreAuthorize("@ss.hasPermi('pacom:tools:saledevice:unbind')")
  @Log(title = "销售设备数据管理", businessType = BusinessType.UPDATE)
  @PutMapping("/unbind")
  public AjaxResult unbind(@RequestBody PacomDeviceBindReq req) {
    String uri = getUri("bind");
    R<String> r = this.restClient.getRestTemplate()
                                 .postForObject(uri, req, R.class);

    return toAjax(1);
  }

  /**
   * 删除角色
   */
  @PreAuthorize("@ss.hasPermi('pacom:tools:saledevice:remove')")
  @Log(title = "销售设备数据管理", businessType = BusinessType.DELETE)
  @DeleteMapping("{id}")
  public AjaxResult remove(@PathVariable String id) {
    String uri = getUri("/delete/" + id);

    ResponseEntity<R> r = this.restClient.getRestTemplate()
                                         .exchange(uri, HttpMethod.DELETE, HttpEntity.EMPTY, R.class);

    return toAjax(1);
  }
}
